package com.lottery.utils;

import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lottery.dto.ObtainDataDto;
import com.lottery.obtainData.ObtainDataUtils;

public class AchieveDataUtil {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    // 数字切割
    public static String numberSpilt(String number) {
        String[] num = number.split(",");
        // num[(num.length - 1)] = num[(num.length - 1)].substring(0, 2);
        Integer[] intArrays = integerArray(num);
        if (intArrays == null) {
            return null;
        }
        Arrays.sort(intArrays);
        List<Integer> list = new ArrayList<>();
        int b = 0;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 18; i++) {
            b += intArrays[i];
            if ((i + 1) % 6 == 0) {
                list.add(quShu(b));
                b = 0;
            }
        }
        String aa = sb.append(list.get(0)).append(",").append(list.get(1)).append(",").append(list.get(2)).toString();
        return aa;
    }

    // 取数字个位数的方法
    public static int quShu(int number) {

        return number % 10;

        // String result = "" + number;
        // int length = result.length();
        // return Integer.parseInt(String.valueOf(result.charAt(length - 1)));
    }

    // 将字符串数组装换成integer类型数组
    public static Integer[] integerArray(String[] param) {
        // List<Integer> LString = new ArrayList<Integer>();
        // Integer[] result = null;
        //
        // for (int i = 0; i < param.length; i++) {
        // LString.add(new Integer(param[i]));
        // }
        // int size = LString.size();
        // result = (Integer[]) LString.toArray(new Integer[size]);
        // return result;

        Integer[] result = new Integer[18];
        if (param.length <= 18) { // param一般长20，最后一个不可用
            return null;
        }
        for (int i = 0; i < 18; i++) {
            result[i] = Integer.parseInt(param[i]);
        }

        return result;
    }

    public static ObtainDataDto getObtainInfo(String url) {

        String httpRequest = ObtainDataUtils.obtainData(url);
        if (httpRequest == null) {
            return null;
        }

        JSONObject parseObject = ObtainDataUtils.stringToJson(httpRequest);

        if (parseObject == null || parseObject.size() == 0) {
            return null;
        }
        ObtainDataDto obtainData = new ObtainDataDto();

        JSONObject nowExpectInfo = JSON.parseObject(String.valueOf(parseObject.getJSONArray("data").get(0)));
        obtainData.setExpect(nowExpectInfo.getString("expect"));
        obtainData.setOpencode(nowExpectInfo.getString("opencode"));
        obtainData.setOpentime(nowExpectInfo.getString("opentime"));
        try{
            int nextExpect = Integer.parseInt(obtainData.getExpect()) + 1;
            obtainData.setNextExpect(nextExpect + "");
            String nextOpenTime = null;
            int hours = Integer.parseInt(obtainData.getOpentime().substring(11, 13));
            int minite = Integer.parseInt(obtainData.getOpentime().substring(14, 16));
            if (hours == 23 && minite >= 57) {
                nextOpenTime = DateUtil.getDateFromString(obtainData.getOpentime(), "yyyy-MM-dd", 10) + " 09:07:00";
                obtainData.setNextOpenTime(nextOpenTime);
            } else if ((hours >= 0 && hours < 9) || (hours == 9 && minite < 7)) {
                nextOpenTime = DateUtil.getFormatDate("yyyy-MM-dd") + " 09:07:00";
                obtainData.setNextOpenTime(nextOpenTime);
            } else {
                nextOpenTime = obtainData.getOpentime().substring(0, 10);
                int delay = 5;
                minite = minite + delay;
                if (minite >= 60) {
                    hours++;
                    minite = minite % 60;
                }
                String time = String.format(" %02d:%02d:00", hours, minite);
                nextOpenTime = nextOpenTime + time;
                obtainData.setNextOpenTime(nextOpenTime);
            }
        }catch (NullPointerException e){
        }
        return obtainData;
    }

    // 校验开奖信息的json数据,并将当天和前一天的开奖信息封装
    public static Map<String, ObtainDataDto> GetOpencodeInfo(String url) {
        Map<String, ObtainDataDto> map = new HashMap<>();
        String today = DateUtil.getFormatDate("yyyy-MM-dd");
        String yesterday = changeDate(today);
        String urlToday = modifyURL(url, today);
        String urlYesterday = modifyURL(url, yesterday);
        // 获取今天一开奖的期号
        Map<String, ObtainDataDto> todayExpect = getExpectArrays(urlToday);
        for (Map.Entry<String, ObtainDataDto> entry : todayExpect.entrySet()) {
            map.put(entry.getKey(), entry.getValue());
        }
        // 获取昨天的开奖期号,封装进map
        Map<String, ObtainDataDto> yesterdayExpect = getExpectArrays(urlYesterday);
        for (Map.Entry<String, ObtainDataDto> entry : yesterdayExpect.entrySet()) {
            map.put(entry.getKey(), entry.getValue());
        }

        return map;

    }

    // 将固定时间的期号查询并封装成集合
    private static Map<String, ObtainDataDto> getExpectArrays(String urlToday) {
        Map<String, ObtainDataDto> map = new HashMap<>();
        String httpRequest = ObtainDataUtils.obtainData(urlToday);
        if (httpRequest == null) {
            return null;
        }

        JSONObject parseObject = ObtainDataUtils.stringToJson(httpRequest);

        if (parseObject == null) {
            return null;
        }

        // JSONObject nowExpectInfo =
        // JSON.parseObject(String.valueOf(parseObject.getJSONArray("data")));
        JSONArray array = parseObject.getJSONArray("data");
        ObtainDataDto obt = null;
        for (Object object : array) {
            obt = new ObtainDataDto();
            JSONObject nowExpectInfo = JSON.parseObject(String.valueOf(object));
            obt.setOpencode(nowExpectInfo.getString("opencode"));
            obt.setOpentime(nowExpectInfo.getString("opentime"));
            map.put(nowExpectInfo.getString("expect"), obt);
        }
        return map;
    }

    // 将时间提前一天
    public static String changeDate(String time) {
        Date today = null;
        try {
            today = DateUtil.getDateFromString(time, "yyyy-MM-dd");
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Format ctime = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        c.add(Calendar.DAY_OF_MONTH, -1);
        Date startDate = c.getTime();
        return ctime.format(startDate);
    }

    // 重写url地址
    public static String modifyURL(String url, String time) {
        StringBuffer sb = new StringBuffer();
        url = url.replaceFirst("newly", "daily");
        String urlNew = sb.append(url).append("&date=").append(time).toString();
        return urlNew;
    }

    public static String robotDivision(String s) {

        Pattern p = Pattern.compile("[\\u4e00-\\u9fa5]+|\\d+");
        Matcher m = p.matcher(s);
        String group = "";
        if (m.find()) {
            group = m.group();
        }
        String betting = group;
        String betNumber = s.substring(betting.length());
        String ss = "下注 " + betting + " " + betNumber;
        return ss;
    }

    public static ObtainDataDto getObtainBjscInfo(String url) {
        String httpRequest = ObtainDataUtils.obtainData(url);
        if (httpRequest == null) {
            return null;
        }

        JSONObject parseObject = ObtainDataUtils.stringToJson(httpRequest);

        if (parseObject == null) {
            return null;
        }
        ObtainDataDto obtainData = new ObtainDataDto();

        JSONObject nowExpectInfo = JSON.parseObject(String.valueOf(parseObject.getJSONArray("data").get(0)));
        obtainData.setExpect(nowExpectInfo.getString("expect"));
        obtainData.setOpencode(nowExpectInfo.getString("opencode"));
        obtainData.setOpentime(nowExpectInfo.getString("opentime"));

        int nextExpect = Integer.parseInt(obtainData.getExpect()) + 1;
        obtainData.setNextExpect(nextExpect + "");
        String nextOpenTime = null;
        int hours = Integer.parseInt(obtainData.getOpentime().substring(11, 13));
        int minite = Integer.parseInt(obtainData.getOpentime().substring(14, 16));
        if (hours == 23 && minite >= 57) {
            nextOpenTime = DateUtil.getDateFromString(obtainData.getOpentime(), "yyyy-MM-dd", 10) + " 09:07:00";
            obtainData.setNextOpenTime(nextOpenTime);
        } else if (hours >= 0 && hours < 9) {
            nextOpenTime = DateUtil.getFormatDate("yyyy-MM-dd") + " 09:07:00";
            obtainData.setNextOpenTime(nextOpenTime);
        } else {
            nextOpenTime = obtainData.getOpentime().substring(0, 10);
            int delay = 5 - (minite % 5);
            minite = minite + delay;
            if (minite >= 60) {
                hours++;
                minite = minite % 60;
            }
            String time = String.format(" %02d:%02d:00", hours, minite);
            nextOpenTime = nextOpenTime + time;
            obtainData.setNextOpenTime(nextOpenTime);
        }

        return obtainData;
    }
}
